package com.blacktea.webmagic.demo.pipeline;

import cn.hutool.core.lang.Assert;
import com.blacktea.webmagic.demo.domain.Download;
import com.blacktea.webmagic.demo.strategy.DownloadContext;
import com.blacktea.webmagic.demo.util.WebMagicUtil;
import lombok.extern.slf4j.Slf4j;
import us.codecraft.webmagic.ResultItems;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description:
 * @author: black tea
 * @date: 2021/9/24 10:58
 */
@Slf4j
public class ItemDownloadPipeline extends AbstractDownloadPipeline{

    private final AtomicInteger imgInteger = new AtomicInteger(0);
    private final AtomicInteger mdInteger = new AtomicInteger(0);

    private Download download;

    private ItemDownloadPipeline() {
    }

    private ItemDownloadPipeline(Download download) {
        Assert.notNull(download);
        this.download = download;
    }

    public static ItemDownloadPipeline download(Download download) {
        return new ItemDownloadPipeline(download);
    }

    @Override
    public void download(ResultItems resultItems) {
        Map<String, Map<String, String>> dataMap = WebMagicUtil.getDataMap(download, resultItems,null,imgInteger,mdInteger);
        DownloadContext.context(download).ifPresent(context -> {
            context.executDownloadZip(download,dataMap);
        });
    }
}
